<?php
if (!defined('__TYPECHO_ROOT_DIR__')) exit;
//加载七牛官方PHPSDK
require_once __DIR__ . '/autoload.php';

/**
 * 七牛上传插件
 *
 * @package qiniu
 * @author zlh
 * @version 1.0.0
 * @link http://zhanglihu.com
 */
class Qiniu_Plugin implements Typecho_Plugin_Interface
{
    /**
     * 激活插件方法,激活失败,直接抛出异常
     * @access public
     * @return void
     * @throws Typecho_Plugin_Exception
     */
    public static function activate()
    {
        Typecho_Plugin::factory('admin/menu.php')->navBar = array('Qiniu_Plugin', 'render');
        Typecho_Plugin::factory('admin/header.php')->header = array('Qiniu_Plugin', 'registerJs');
    }

    /**
     * 禁用插件方法,如果禁用失败,直接抛出异常
     * @static
     * @access public
     * @return void
     * @throws Typecho_Plugin_Exception
     */
    public static function deactivate(){
    }

    /**
     * 获取插件配置面板
     *
     * @access public
     * @param Typecho_Widget_Helper_Form $form 配置面板
     * @return void
     */
    public static function config(Typecho_Widget_Helper_Form $form)
    {
        $ak = new Typecho_Widget_Helper_Form_Element_Text('ak', NULL, '输入AK', _t('七牛AK'));
        $form->addInput($ak);
        $ak = new Typecho_Widget_Helper_Form_Element_Text('sk', NULL, '输入sk', _t('七牛SK'));
        $form->addInput($ak);
        $bucket = new Typecho_Widget_Helper_Form_Element_Text('bucket', NULL, '输入bucket', _t('七牛bucket'));
        $form->addInput($bucket);
        $domain = new Typecho_Widget_Helper_Form_Element_Text('domain', NULL, '输入上传地址', _t('七牛上传地址'));
        $form->addInput($domain);
    }

    /**
     * 个人用户的配置面板
     *
     * @access public
     * @param Typecho_Widget_Helper_Form $form
     * @return void
     */
    public static function personalConfig(Typecho_Widget_Helper_Form $form)
    {
    }

    /**
     * 获取七牛上传的token
     */
    public static function getUpToken()
    {
        $plugin = Typecho_Widget::widget('Widget_Options')->plugin('Qiniu');
        $ak = $plugin->ak;
        $sk = $plugin->sk;
        $bucket = $plugin->bucket;
        if(empty($ak) || empty($sk) || empty($bucket))
        {
            return false;
        }
        // 构建鉴权对象
        $auth = new Qiniu\Auth($ak, $sk);
        // 生成上传 Token
        $token = $auth->uploadToken($bucket);
        return empty($token) ? false : $token;
    }

    public static function registerJs($header)
    {
        $domain = Typecho_Widget::widget('Widget_Options')->plugin('Qiniu')->domain;
        $token = self::getUpToken();
        return $header . '<script src = "https://cdn.staticfile.org/qiniu-js-sdk/1.0.14-beta/qiniu.js"></script><script>var qiniuConfig  = {"token":"'.$token.'", "domain":"'. $domain .'"}</script>';
    }

    public static function render()
    {

    }

}